import axios from 'axios'

const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 30000,
  withCredentials: false,
})

service.interceptors.request.use(
  (request) => {
    const { data } = request
    openLoading()
    //  TODO  添加token
    return request
  },
  (err) => {
    Message.error('无法发送请求')
    return Promise.reject(err.data)
  },
)

//拦截返回值
service.interceptors.response.use(
  async (response) => {
    // closeLoading()
    const {
      data: res,
      data: { code, data, msg },
    } = response
    // 未登录的过滤，
    closeLoading()
    if (code != 200) {
      if (code === 403) {
        const { origin } = window.location
        const href = `${origin}/user/login`
        if (window.location.href != href) {
          console.error('未登录')
          window.location.href = href
        }
      } else {
        Message.error(msg || '程序异常')
      }
      return Promise.reject(res)
    }
    return Promise.resolve(data)
  },
  (err) => {
    closeLoading()
    if (!err.request) Message.error('请求异常')
    else {
      const { status: code } = err.request
      if (code == 404) Message.error('未知的请求')
      else Message.error('请求服务器异常')
    }
    return Promise.reject(err)
  },
)
export default service
